<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NAvatar,
  NButton,
  NEllipsis,
  NFlex,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NPopconfirm, NSelect,
  NSwitch,
  NTag,
  useMessage
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import TheIcon from '@/components/icon/TheIcon.vue'
import { getToken } from '@/utils'
import { renderIcon } from '@/utils'
import { useCRUD } from '@/composables'
import api from '@/api'
import {router} from "@/router";
const base_path = import.meta.env.VITE_BASE
import default_image from "@/assets/images/mz.jpg"

defineOptions({ name: '额度申请记录' })
const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')

const {
  modalVisible,
  modalTitle,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '额度申请记录',
  initForm: {},
  doCreate: api.createCustomersFollow,//接口地址修改
  doUpdate: api.updateCustomersFollow,//接口地址修改
  doDelete: api.deleteCustomersFollow,//接口地址修改
  refresh: () => $table.value?.handlerefresh(),
})

const data = reactive({
  customer_level: [],
  token: getToken(),
  uploadAction: base_path+'api/customers/customers_list/file',
  onLevelData: [],
  selectValue:'',
  show_excel:false,
  show_info:false,
  c_type:[],
  c_status:[],
  fileList1: [],
  fileList2: [],
  fileList3: [],
});


function formatTimestamp(timestamp) {
  const date = new Date(timestamp)
  const pad = (num) => num.toString().padStart(2, '0')
  const year = date.getFullYear()
  const month = pad(date.getMonth() + 1) // 月份从0开始，所以需要+1
  const day = pad(date.getDate())
  const hours = pad(date.getHours())
  const minutes = pad(date.getMinutes())
  const seconds = pad(date.getSeconds())
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}


const datetimeRange = ref()
const handleDateRangeChange = (value) => {
  queryItems.value.start_time = formatTimestamp(value[0])
  queryItems.value.end_time = formatTimestamp(value[1])
}

onMounted(() => {
  api.getStatusLevel().then((res) => (data.c_status = res.data))
  $table.value?.handleSearch()
})

//表单规则部分
const addAPIRules = {
  name: [
    {
      required: true,
      message: '请输入会员昵称',
      trigger: ['input', 'blur'],
    },
  ],
  role_id: [
    {
      required: true,
      message: '请选择会员级别',
      trigger: ['blur', 'change'],
      type: 'number',
    },
  ],
}


function show_info(row){
  data.show_info = true
  data.select_customer = row
}

//table表头
const columns = [
  {
    title: '企业名称',
    key: 'qymc',
    align: 'center',
    width: '300',
    fixed: 'left',
  },
  {
    title: '企业税号',
    key: 'qysh',
    align: 'center',
    width: '200',

  },

  {
    title: '法人姓名',
    key: 'name',
    align: 'center',
    width: '80',
    ellipsis: { tooltip: true },
  },
  {
    title: '银行卡号',
    key: 'yh_no',
    width: '200',
    align: 'center',
  },
  {
    title: '开户行',
    key: 'yh_khh',
    width: '100',
    align: 'center',
  },
    {
    title: '预留手机号',
    key: 'yh_phone',
    width: '120',
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '提交时间',
    key: 'created_at',
    width: '200',
    align: 'center',
    ellipsis: { tooltip: true },
  },

]

//上传头像
const message = useMessage();

const customRequestMethod = (options) => {
  const { file } = options.file;
  const formData = new FormData();
  formData.append('file', file);
  fetch(data.uploadAction, {
    method: 'POST',
    headers: options.headers,
    body: formData,
  })
      .then((response) => response.json())
      .then((data) => {
        console.log(data, 'datatat');
        if (data.code == 200) {
          modalForm.value.avatar = data.data.url
          message.success('文件上传成功');
          options.onProgress(data);
        }else{
          message.error(data.msg);
        }
      })
};
// 修改用户禁用状态
async function handleUpdateDisable(row) {
  if (!row.id) return
  row.publishing = true
  row.is_active = row.is_active === false ? true : false
  row.publishing = false
  try {
    await api.updateCustomer(row)
    $message?.success(row.is_active ? '已取消禁用该用户' : '已禁用该用户')
    $table.value?.handlerefresh()
  } catch (err) {
    // 有异常恢复原来的状态
    row.is_active = row.is_active === false ? true : false
  } finally {
    row.publishing = false
  }
}

async function handleUpdateUser(row) {
  if (!row.id) return
  row.publishing = true
  row.is_user = row.is_user === false
  row.publishing = false
  try {
    await api.updateCustomer(row)
    $message?.success(row.is_user ? '已设置为员工': '已取消')
    $table.value?.handlerefresh()
  } catch (err) {
    // 有异常恢复原来的状态
    row.is_user = row.is_user === false
  } finally {
    row.publishing = false
  }
}

//获取默认会员类型
async function getcosutomer_level() {
  let ret = await api.getCustomerLevel()
  data.customer_level = ret.data
}

//获取上级部门id
async function onleves(query) {
  let val = await api.getLeves({key:query})
  data.onLevelData = val.data
}

//异步下拉获取上级
const loadingRef = ref(false);
const optionsRef = ref([]);
const handleLeves = (query) => {
  if (!query.length) {
    optionsRef.value = [];
    return;
  }
  onleves(query)
  loadingRef.value = true;
  // data.selectValue
  window.setTimeout(() => {
    data.onLevelData.value = data.onLevelData.filter(
        (item) => ~item.label.indexOf(query)
    );
    loadingRef.value = false;
  }, 1e3);
}

async function  on_excel(){
  await api.onCustomerExcel({start_time:queryItems.value.start_time,end_time:queryItems.value.end_time})
  data.show_excel = true
  //$message?.success('正在生成下载文件,请前往下载中心查看')
}
function go_excel(){
  router.push({ path: '/downloads/list' });
}

</script>

<template>
  <!-- 业务页面 -->
  <CommonPage show-footer title="额度申请记录">

    <CrudTable ref="$table" v-model:query-items="queryItems" :columns="columns" :get-data="api.getCustomersFollow"
               :scroll-x="1200" >
      <template #queryBar>
        <QueryBarItem label="公司名称" :label-width="70">
          <NInput v-model:value="queryItems.qymc" clearable type="text" placeholder="请输入公司名称"
                  @keypress.enter="$table?.handleSearch()" />
        </QueryBarItem>
        <QueryBarItem label="法人姓名" :label-width="70">
          <NInput v-model:value="queryItems.name" clearable type="text" placeholder="请输入法人姓名"
                  @keypress.enter="$table?.handleSearch()" />
        </QueryBarItem>
        <QueryBarItem label="手机号码" :label-width="70">
          <NInput v-model:value="queryItems.phone" clearable type="text" placeholder="请输入手机号"
                  @keypress.enter="$table?.handleSearch()" />
        </QueryBarItem>

      </template>
    </CrudTable>


  </CommonPage>
</template>
